package com.android.kotlincoroutinemvvmdemo.itemdecoration
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Rect
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import com.android.kotlincoroutinemvvmdemo.R

class StackItemDecoration(context: Context) : RecyclerView.ItemDecoration() {

    private val mContext = context

    private val dividerHeight = context.resources.getDimension(R.dimen.dp_1).toInt()
    private val leftSpace = 0/*context.resources.getDimension(R.dimen.dp_20).toInt()*/

    private val dividerPaint by lazy {
        Paint(Paint.ANTI_ALIAS_FLAG).apply {
            isAntiAlias = true
            isDither = true
            color = context.resources.getColor(R.color.color_B128C9)
        }
    }

    private val rect by lazy {
        Rect()
    }

    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {
        super.getItemOffsets(outRect, view, parent, state)
        //val childIndex = parent.getChildAdapterPosition(view)
        outRect.bottom = dividerHeight
    }

    override fun onDraw(canvas: Canvas, parent: RecyclerView, state: RecyclerView.State) {
        super.onDraw(canvas, parent, state)

        val itemCount = parent.adapter?.itemCount ?: 0

        for (i in 0.until(itemCount)) {
            val child = parent.layoutManager?.getChildAt(i)
            val bottom = child?.bottom ?: 0
            Log.d(TAG, "bottom:${bottom}")
            val childWidth = child?.measuredWidth ?: 0
            Log.d(TAG, "childWidth:${childWidth}")
            if (childWidth > 0) {
                rect.set(leftSpace, bottom, childWidth, bottom + dividerHeight)
                canvas.drawRect(rect, dividerPaint)
            }
        }
    }

    fun updatePaintColor(uiModeNight: Boolean) {
        if (uiModeNight) {
            dividerPaint.color = mContext.resources.getColor(R.color.black)
        } else {
            dividerPaint.color = mContext.resources.getColor(R.color.color_B128C9)
        }
    }

    companion object {
        const val TAG = "StackContainerItemDecoration"
    }

}